/*
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.content;

import hk.com.carfield.core.Config;
import hk.com.carfield.util.StringUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;

public final class Text implements Content, Editable, Describable {
	private final Config config;

	private final File file;

	private final String content;

	public Text(final Config config, final File file) {
		super();
		this.config = config;
		this.file = file;
		try {
			final InputStreamReader is = new InputStreamReader(new FileInputStream(file), "UTF-8");
			content = StringUtil.text2Html(is);
			is.close();
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
	}

	public final String process(final Request req) throws IOException {
		if (req != null) {
			FileUtils.writeStringToFile(file, req.getParameter("content"), "UTF-8");
		}
		final InputStream is = new FileInputStream(file);
		try {
			return "<TEXTAREA NAME=content rows=\"16\" cols=\"100\">"
					+ StringEscapeUtils.escapeHtml(IOUtils.toString(is, "UTF-8")) + "</TEXTAREA><br>";
		} finally {
			is.close();
		}
	}

	public String getThumbnail() {
		// TODO add default icon for difference type... should get through
		// servlet so that one jar is ok
		return null;
	}

	public String getContent() {
		return content;
	}

	public String getDesc() {
		return content;
	}
}